from django.shortcuts import render
from django.http import JsonResponse
from .models import Auth
from django.contrib.sessions.models import Session
from datetime import datetime
from .models import Cart,Auth,Order
from goods.models import GoodsInfo
import json
import requests
from seaWind.config import *

def c2s(appid,code):
    return code2session(appid,code)

def code2session(appid,code):
    API = 'https://api.weixin.qq.com/sns/jscode2session?'
    params = 'appid=%s&secret=%s&js_code=%s&grant_type=authorization_code'%(appid,SECRECT_KEY,code)
    url = API + params
    response = requests.get(url=url)
    data = json.loads(response.text)
    print(data)
    return data

def get_order_number():
    import random
    import time
    from datetime import datetime
    res1 = str(random.randint(0,10)*10)
    res2 = str(random.randint(0,10)*10)
    res3 = str(int(time.time()))
    return res1+res2+res3


# Create your views here.


def login(request):
    if request.method == "GET":
        if not judge_authed(request):
            request.session["is_authed"] = 0
            response = {"is_authed": 0}
            return JsonResponse(data=response)

    elif request.method== "POST":
        postDataStr = request.body.decode("utf8")
        postData = json.loads(postDataStr)
        code = postData.get("code")
        name = postData.get("nickname")
        response = {}
        response["is_openid"] = 1
        response["is_dataed"] = 1
        if not appid or not code:
            response["is_dataed"] = 0

        data = c2s(appid,code)
        openid = data.get("openid")
        if not openid:
            response["is_openid"] = 0

        if not Auth.objects.filter(openID=openid):
            cartID = Cart.objects.all().count() + 1
            request.session['openID'] = openid
            request.session['is_authorized'] = True
            request.session.set_expiry(datetime(2300, 10, 10))

            cart = Cart(cartID=cartID,goodsInfo1="[]")
            cart.save()

            cartInstance = Cart.objects.filter(cartID=cartID)[0]
            newuser = Auth(openID=openid, nickname=name,cart=cartInstance)
            newuser.save()
            response["is_authed"] = 1
            return JsonResponse(data=response, safe=False)

        c2s(appid, code)
        print("sessionKey过期,")
        res = Session.objects.filter(session_key=openid).delete()
        request.session['openID'] = openid
        request.session['is_authorized'] = True
        request.session.set_expiry(datetime(2300, 10, 10))
        response["is_authed"] = 1
        print(response)
        return JsonResponse(data=response, safe=False)

def order(request):

    if request.method == "GET":
        if not judge_authed(request):
            request.session["is_authed"] = 0
            response = {"is_authed": 0}
            return JsonResponse(data=response)
        response = {}
        openid = request.session.get("openID")
        # openid = request.GET.get("openID")
        ObligationsList = []
        ToBeDeliveredList = []
        ToBereceivedList = []
        totalList = []
        res = Order.objects.select_related().filter(userID__openID=openid)
        if not res.count():
            response["ObligationsList"] = ObligationsList
            response["ToBeDeliveredList"] = ToBeDeliveredList
            response["ToBereceivedList"] = ToBereceivedList
            response["TotalList"] = []
            return JsonResponse(data=response)

        for i in res:
            address = json.loads(i.showAddress)
            print(address)
            goodsInfo = json.loads(i.goodsInfo)
            order_status_text = ""
            if i.paymentStatus == "0":
                if i.orderResult == "0":
                    order_status_text = "已取消"
                else:
                    order_status_text = "待付款"
            elif i.DeliveryStatus == "0":
                if i.orderResult == "0":
                    order_status_text = "已取消"
                else:
                    order_status_text = "待发货"
            elif i.harvestStatus == "0":
                if i.orderResult == "0":
                    order_status_text = "已取消"
                else:
                    order_status_text = "待收货"
            if i.paymentMode == "1":
                offline_pay = 1
            else:
                offline_pay = 0
            dict1 = {"orderID": i.orderID, "orderNumber": i.orderNumber, "createTime": i.joinTime,
                     "addressID": address["id"],"mobile":address.get("mobile"),"consignee":address.get("name"),
                     "full_region":address.get("address"),"address":address.get("detailAddress"),
                     "payGoodsNumber":i.payGoodsNumber,"offline_pay":offline_pay ,
                     "goodsList": goodsInfo,"totalPrice":i.totalPrice,"order_status_text":order_status_text}
            totalList.append(dict1)
        Obligations = res.filter(paymentStatus=0)
        ToBeDelivered = res.filter(DeliveryStatus=0)
        ToBereceived = res.filter(harvestStatus=0)
        if Obligations.count():
            for i in Obligations:
                address = json.loads(i.showAddress)
                goodsInfo = json.loads(i.goodsInfo)
                order_status_text = ""
                if i.paymentStatus == "0":
                    if i.orderResult == "0":
                        order_status_text = "已取消"
                    else:
                        order_status_text = "待付款"
                elif i.DeliveryStatus == "0":
                    if i.orderResult == "0":
                        order_status_text = "已取消"
                    else:
                        order_status_text = "待发货"
                elif i.harvestStatus == "0":
                    if i.orderResult == "0":
                        order_status_text = "已取消"
                    else:
                        order_status_text = "待收货"
                if i.paymentMode == "1":
                    offline_pay = 1
                else:
                    offline_pay = 0
                dict1 = {"orderID": i.orderID, "orderNumber": i.orderNumber, "createTime": i.joinTime,
                         "addressID": address["id"], "mobile": address.get("mobile"), "consignee": address.get("name"),
                         "full_region": address.get("address"), "address": address.get("detailAddress"),
                         "payGoodsNumber": i.payGoodsNumber, "offline_pay": offline_pay,
                         "goodsList": goodsInfo, "totalPrice": i.totalPrice,"order_status_text":order_status_text}
                ObligationsList.append(dict1)

        if ToBeDelivered.count():
            for i in ToBeDelivered:
                address = json.loads(i.showAddress)
                goodsInfo = json.loads(i.goodsInfo)
                order_status_text = ""
                if i.paymentStatus == "0":
                    if i.orderResult == "0":
                        order_status_text = "已取消"
                    else:
                        order_status_text = "待付款"
                elif i.DeliveryStatus == "0":
                    if i.orderResult == "0":
                        order_status_text = "已取消"
                    else:
                        order_status_text = "待发货"
                elif i.harvestStatus == "0":
                    if i.orderResult == "0":
                        order_status_text = "已取消"
                    else:
                        order_status_text = "待收货"
                if i.paymentMode == "1":
                    offline_pay = 1
                else:
                    offline_pay = 0
                dict1 = {"orderID": i.orderID, "orderNumber": i.orderNumber, "createTime": i.joinTime,
                         "addressID": address["id"], "mobile": address.get("mobile"), "consignee": address.get("name"),
                         "full_region": address.get("address"), "address": address.get("detailAddress"),
                         "payGoodsNumber": i.payGoodsNumber, "offline_pay": offline_pay,
                         "goodsList": goodsInfo, "totalPrice": i.totalPrice,"order_status_text":order_status_text}
                ToBeDeliveredList.append(dict1)

        if ToBereceived.count():
            for i in ToBereceived:
                address = json.loads(i.showAddress)
                goodsInfo = json.loads(i.goodsInfo)
                order_status_text = ""
                if i.paymentStatus == "0":
                    if i.orderResult == "0":
                        order_status_text = "已取消"
                    else:
                        order_status_text = "待付款"
                elif i.DeliveryStatus == "0":
                    if i.orderResult == "0":
                        order_status_text = "已取消"
                    else:
                        order_status_text = "待发货"
                elif i.harvestStatus == "0":
                    if i.orderResult == "0":
                        order_status_text = "已取消"
                    else:
                        order_status_text = "待收货"
                if i.paymentMode == "1":
                    offline_pay = 1
                else:
                    offline_pay = 0
                dict1 = {"orderID": i.orderID, "orderNumber": i.orderNumber, "createTime": i.joinTime,
                         "addressID": address["id"], "mobile": address.get("mobile"), "consignee": address.get("name"),
                         "full_region": address.get("address"), "address": address.get("detailAddress"),
                         "payGoodsNumber": i.payGoodsNumber, "offline_pay": offline_pay,
                         "goodsList": goodsInfo, "totalPrice": i.totalPrice,"order_status_text":order_status_text}
                ToBereceivedList.append(dict1)

        response["ObligationsList"] = ObligationsList
        response["ToBeDeliveredList"] = ToBeDeliveredList
        response["ToBereceivedList"] = ToBereceivedList
        response["TotalList"] = totalList

        return JsonResponse(response)

    elif request.method == "POST":
        # if not judge_authed(request):
            # request.session["is_authed"] = 0
            # response = {"is_authed": 0}
            # return JsonResponse(data=response)
        response = {}
        # userID = request.session.get("openID")
        postDataStr = request.body.decode("utf8")
        postData = json.loads(postDataStr)
        userID = postData["openID"]
        if postData.get("orderID"):
            order = Order.objects.filter(orderID=postData["orderID"])[0]
            print(order.orderResult)
            if postData.get("is_cancel"):
                try:
                    order.orderResult = '0'
                    order.save()
                    response["is_cancelCode"] = 1
                    response["is_cancelMsg"] = "已取消"
                except:
                    response["is_cancelCode"] = 0
                    response["is_cancelMsg"] = "取消失败,未知错误"
                return JsonResponse(data=response)
        addressID = postData["addressID"]
        goodsInfo = postData["goodsInfo"]
        totalPrice = str(postData["totalPrice"])
        annocate = postData["annocate"]
        payGoodsNumber = str(postData["payGoodsNumber"])
        paymentMode = postData.get("OfflinePayment")
        paymentMode2 = postData.get("onlinePayment")
        for i in goodsInfo:
            goodsID = i["goodsID"]
            goodsInstance = GoodsInfo.objects.filter(GoodsInfo_ID=goodsID)[0]
            i["list_pic_url"] = goodsInstance.pic_url
            i["goodsNumber"] = goodsInstance.goods_number
            i["name"] = goodsInstance.name
        goodsInfo = json.dumps(goodsInfo)
        paymentStatus = 0
        payMode = ""
        paymentTime = ""
        if paymentMode2:
            paymentStatus = 1
            paymentTime = str(datetime.now())
            payMode = "2"
        elif paymentMode:
            payMode = "1"

        u1 = Auth.objects.filter(openID=userID)[0]
        addrLST = json.loads(u1.shou_address)
        print(addrLST)
        addr = ""
        for i in addrLST:
            if i["id"] == addressID:
                addr = json.dumps(i)
                break
        orderNumber = get_order_number()
        try:
            res = Order.objects.create(orderNumber=orderNumber,userID=u1,showAddress=addr,goodsInfo=goodsInfo,totalPrice=totalPrice,
                                       paymentStatus=paymentStatus,buyerAnnocate=annocate,paymentTime=paymentTime,paymentMode=payMode,
                                       payGoodsNumber=payGoodsNumber)
            res.save()
            response["resultCode"] = 1
            response["resultMsg"] = "订单提交成功"
            return JsonResponse(data=response)
        except:
            response["resultMsg"] = "订单提交失败未知错误"
            response["reCode"] = 0

            return JsonResponse(data=response)

    elif request.method == "DELETE":
        if not judge_authed(request):
            request.session["is_authed"] = 0
            response = {"is_authed": 0}
            return JsonResponse(data=response)
        deleteDataStr = request.body.decode("utf8")
        deleteData = json.loads(deleteDataStr)
        orderID = deleteData["orderID"]
        response = {}
        try:
            Order.objects.filter(orderID=orderID).delete()
            response["resultCode"] = 1
            response["resultMsg"] = "删除订单操作成功"
        except:
            response["resultCode"] = 0
            response["resultMsg"] = "删除订单操作失败"
        return JsonResponse(data=response)

def orderDetail(request):
    if request.method == "GET":
        if not judge_authed(request):
            request.session["is_authed"] = 0
            response = {"is_authed": 0}
            return JsonResponse(data=response)
        openid = request.session.get("openID")
        orderID = request.GET.get("orderID")
        i = Order.objects.filter(orderID=orderID)[0]
        address = json.loads(i.showAddress)
        goodsInfo = json.loads(i.goodsInfo)

        handleOption = {"cancel":1,"pay":1,}
        order_status_text = ""
        if i.paymentStatus == "0":
            order_status_text = "待付款"
            if i.orderResult == "0":
                order_status_text = "已取消"
                handleOption["delete"] = 1
                handleOption["cancel"] = 0
        elif i.DeliveryStatus == "0":
            order_status_text = "待发货"
            if i.orderResult == "0":
                order_status_text = "已取消"
                handleOption["delete"] = 1
                handleOption["cancel"] = 0
        elif i.harvestStatus == "0":
            order_status_text = "待收货"
            if i.orderResult == "0":
                order_status_text = "已取消"
                handleOption["delete"] = 1
                handleOption["cancel"] = 0

        if i.paymentMode == "1":
            offline_pay = 1
        else:
            offline_pay = 0
        response = {"orderID": i.orderID, "orderNumber": i.orderNumber, "createTime": i.joinTime,
                 "addressID": address["id"], "mobile": address.get("mobile"), "consignee": address.get("name"),
                 "full_region": address.get("address"), "address": address.get("detailAddress"),
                 "payGoodsNumber": i.payGoodsNumber, "offline_pay": offline_pay,
                 "goodsList": goodsInfo, "totalPrice": i.totalPrice,"postscript":i.buyerAnnocate,
                   "handleOption":handleOption,"order_status_text":order_status_text}
        return JsonResponse(data=response)

def checkedAddress(request):

    if request.method == "GET":
        if not judge_authed(request):
            request.session["is_authed"] = 0
            response = {"is_authed": 0}
            return JsonResponse(data=response)
        openid = request.session.get("openID")
        response = {}
        # openid = request.GET.get("openID")
        res = Auth.objects.filter(openID=openid)[0]
        addres = json.loads(res.shou_address)
        for i in addres:
            if i.get("is_default"):
                response["is_default"] = 1
                response["addressList"] = i
                return JsonResponse(response)
            else:
                pass
        response["is_default"] = 0
        return JsonResponse(data=response)

def address(request):

    if request.method == "GET":
        if not judge_authed(request):
            request.session["is_authed"] = 0
            response = {"is_authed": 0}
            return JsonResponse(data=response)
        response = {}
        openid = request.session.get("openID")
        # openid = request.GET.get("openID")
        res = Auth.objects.filter(openID=openid)[0]
        addres = json.loads(res.shou_address)
        response["addressList"] = addres
        return JsonResponse(data=response)

    elif request.method == "POST":
        if not judge_authed(request):
            request.session["is_authed"] = 0
            response = {"is_authed": 0}
            return JsonResponse(data=response)
        response = {}
        openid = request.session.get("openID")
        postDataStr = request.body.decode("utf8")
        postData = json.loads(postDataStr)
        # openid = postData.get("openID")
        result = postData.get("id")
        judgeRes = type(result) == int
        res = Auth.objects.filter(openID=openid)[0]

        addr = res.shou_address
        addrList = json.loads(addr)
        if addr == "[]":
            postData["id"] = 0
            addrList.append(postData)
            res.shou_address = json.dumps(addrList)
            res.save()
            return JsonResponse(data={"alter_resultMsg":"添加成功"})
        elif judgeRes:
            for i in addrList:
                if i["id"] == postData.get("id"):
                    i.update(postData)
                    break
            res.shou_address = json.dumps(addrList)
            res.save()
            response["alter_result"] = 1
            response["alter_resultMsg"] = "增加地址操作成功"
            return JsonResponse(data=response)
        else:
            postData["id"] = addrList[0]["id"]+1
            addrList.insert(0,postData)
            try:
                res.shou_address = json.dumps(addrList)
                res.save()
                response["alter_result"] = 1
                response["alter_resultMsg"] = "增加地址操作成功"
                return JsonResponse(data=response)
            except:
                response["alter_result"] = 0
                response["alter_resultMsg"] = "增加地址操作失败"
                return JsonResponse(data=response)

    elif request.method == "DELETE":
        if not judge_authed(request):
            request.session["is_authed"] = 0
            response = {"is_authed": 0}
            return JsonResponse(data=response)

        response = {}
        deleteDataStr = request.body.decode("utf8")
        deleteData = json.loads(deleteDataStr)
        openid = request.session.get("openID")
        # openid = deleteData.get("openID")
        res = Auth.objects.filter(openID=openid)[0]
        addr = res.shou_address
        addrList = json.loads(addr)
        for i in addrList:
            if i["id"] == deleteData["id"]:
                addrList.remove(i)
                try:
                    res.shou_address = json.dumps(addrList)
                    res.save()
                    response["alter_result"] = 1
                    response["alter_resultMsg"] = "删除地址操作成功"
                    return JsonResponse(data=response)
                except:
                    response["alter_result"] = 0
                    response["alter_resultMsg"] = "删除地址操作失败"
                    return JsonResponse(data=response)

def cartGoodsCount(request):
    if not judge_authed(request):
        response = {"goodsCount": 0}
        return JsonResponse(data=response)

    openid = request.session.get("openID")
    # openid = request.GET.get("openID")
    u1 = Auth.objects.filter(openID=openid)[0]
    CartGoods = Cart.objects.filter(cartID=u1.cart.cartID)[0].goodsInfo1
    CartGoodsLst = json.loads(CartGoods)
    CartCount = len(CartGoodsLst)
    response = {"goodsCartCount": CartCount}
    return JsonResponse(data=response)

def cartGoods(request):
    if request.method == "GET":
        CartGoodsLst = []
        if not judge_authed(request):
            response = {"goodsCartCount":0,"goodsCartList":CartGoodsLst}
            return JsonResponse(data=response)

        openid = request.session.get("openID")
        # openid = request.GET.get("openID")
        u1 = Auth.objects.filter(openID=openid)[0]
        CartGoods = Cart.objects.filter(cartID=u1.cart.cartID)[0].goodsInfo1
        CartGoodsLst = json.loads(CartGoods)
        # CartCount = len(CartGoodsLst)
        response = {"cartGoods":CartGoodsLst}
        return JsonResponse(data=response)

    elif request.method == "POST":
        if not judge_authed(request):
            response = {"goodsCount":0}
            return JsonResponse(data=response)
        openid = request.session.get("openID")
        postDataStr = request.body.decode("utf8")
        postData = json.loads(postDataStr)
        # openid = postData["openID"]
        goodsid = postData["id"]
        number = postData["number"]
        cart1 = Auth.objects.filter(openID=openid)[0]
        cart = Cart.objects.filter(cartID=cart1.cart.cartID)[0]
        CartGoodsLst = json.loads(cart.goodsInfo1)

        lst = []
        for i in CartGoodsLst:
            if i["id"] == goodsid:
                if i["goods_specifition_name_value"] == postData.get("checkedValues"):
                    lst.append(0)
                else:
                    lst.append(1)
            else:
                lst.append(0)
        if 1 in lst:
            index = lst.index(1)
            CartGoodsLst[index]["number"] = number
            cart.goodsInfo1 = json.dumps(CartGoodsLst)
            cart.save()
            cartGoodsCount = len(CartGoodsLst)
            response = {"cartGoodsCount": cartGoodsCount}
            return JsonResponse(data=response)
        else:
            checked_value = postData["checkedValues"]
            goodinfo = GoodsInfo.objects.filter(GoodsInfo_ID=goodsid)[0]

            cartGoodsDict = {"id":goodinfo.GoodsInfo_ID,"name":goodinfo.name,"goods_specifition_name_value":checked_value,
                             "retail_price":goodinfo.retail_price,"pic_url":goodinfo.pic_url,"goods_number":goodinfo.goods_number,
                             "number":number}

            CartGoodsLst.insert(0,cartGoodsDict)
            cart.goodsInfo1 = json.dumps(CartGoodsLst)
            cart.save()
            cartGoodsCount = len(CartGoodsLst)
            response = {"cartGoodsCount":cartGoodsCount}
            return JsonResponse(data=response)

    elif request.method == "DELETE":
        if not judge_authed(request):
            response = {"goodsCount":0}
            return JsonResponse(data=response)
        openid = request.session.get("openID")
        deleteDataStr = request.body.decode("utf8")
        deleteData = json.loads(deleteDataStr)
        # openid = deleteData["openID"]
        cart1 = Auth.objects.filter(openID=openid)[0]
        cart = Cart.objects.filter(cartID=cart1.cart.cartID)[0]
        CartGoodsLst = json.loads(cart.goodsInfo1)
        for i in CartGoodsLst:
            if i["id"] == deleteData["id"]:
                CartGoodsLst.remove(i)
                saveCartGoodsLst = json.dumps(CartGoodsLst)
                cart.goodsInfo1 = saveCartGoodsLst
                cart.save()
                break
        cart = Cart.objects.filter(cartID=cart1.cart.cartID)[0]
        CartGoodsLst = json.loads(cart.goodsInfo1)
        response = {"resultMsg":"操作成功","cartGoods":CartGoodsLst}
        return JsonResponse(data=response)


def judge_authed(request):
    is_authed = False
    if request.session.get("is_authorized"):
        is_authed = True
    return is_authed
